package com.skjanyou.applicationcase.websocket;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.java_websocket.WebSocket;

import com.skjanyou.applicationcase.util.RobotUtil;
import com.skjanyou.applicationcase.util.WindowsUtil;
import com.skjanyou.server.api.inter.Server;

public class WebsocketServer implements Server,Runnable {
	private Thread thread;
	private ImageWebsocket websocket;
	private volatile boolean isRunning;
	private int port;
	@SuppressWarnings("unused")
	private String contextPath;
	
	public WebsocketServer( int port ,String contextPath ){
		this.port = port;
		this.contextPath = contextPath;
		websocket = new ImageWebsocket(this.port);
		thread = new Thread(this);
	}
	
	@Override
	public Server startup() {
		websocket.start();
		isRunning = true;	
		thread.start();
		return this;
	}

	@Override
	public boolean isAlive() {
		return isRunning;
	}

	@Override
	public Server shutdown() {
		try {
			websocket.stop();
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
		isRunning = false;
		return this;
	}

	@Override
	public void run() {
		BufferedImage image = null;
		Dimension dim = WindowsUtil.getScreenSize();
		ByteArrayOutputStream baos = null;
		
		try{
			while( isRunning ){
				image = RobotUtil.createScreenCapture(0,0,(int)dim.getWidth(),(int)dim.getHeight());
				baos = new ByteArrayOutputStream();
				ImageIO.write(image, "png", baos);
				baos.flush();
				byte[] bytes = baos.toByteArray();
				synchronized( WebsocketSession.list ) {
					for( WebSocket socket :  WebsocketSession.list ){
						socket.send(bytes);
					}
				}
				Thread.sleep(30);
				
			}
		} catch( InterruptedException | IOException e){

		}	
	}

}
